<?php

namespace App\Http\Controllers\Admin\Permission;

use App\Http\Controllers\Controller;
use App\Models\Permission;
use App\Models\Role;
use App\Traits\Controllers\AdminTraits;
use App\Traits\Controllers\UpdateStatusTraits;
use App\Transformers\Role\RoleTransformer;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class RoleController extends Controller
{
    //角色管理的增删改查
    use AdminTraits;
    use UpdateStatusTraits;

    //定义模型和transformer
    public $model = Role::class;
    public $transformer = RoleTransformer::class;

    /**
     * 参数验证规则
     */
    public function rules(Request $request): array
    {
        switch ($request->method()) {
            case 'GET':
                return [];
                break;
            case 'PATCH':
            case 'PUT':
            case 'POST':
                return [
                    'name' => 'required|min:5|max:16',
                ];
            break;
        }
        return [

        ];
    }
    public function ruleMessages(): array
    {
        return [
            'name.required' => '英文名称 不能为空',
            'name.min' => '英文名称 必须至少包含5个字段',
            'name.max' => '英文名称 最多包含16个字段',
        ];
    }

    /**
     * 保存
     */
    public function store(Request $request)
    {
        $this->validateData($request);
        // 保存创建人
        //$request->offsetSet('system_admin_id', $this->admin_user('id'));
        $model = $this->getQuery()->fill($request->all());

        $model->save();

        $model->permissions()->attach($request->permission);

        return $this->response->created();
    }

    /**
     * 更改
     */
    public function update($id,Request $request)
    {
        //验证用户凭证信息
        $this->validateData($request);

        $data = $this->getQuery()->findOrFail($id);

        if ($this->policy) {

            $this->authorize('update', $data);
        }
        $data->fill($request->all());

        $data->save();
        //先删除   多对多
        $data->permissions()->detach();

        $data->permissions()->attach($request->permission);

        return $this->response->created();
    }
}
